package com.example.star.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.api_service.ApiUser;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;
import com.example.star.view.center.ChangeAvatarActivity;
import com.example.star.view.center.FinishActivity;
import com.example.star.view.center.FollowActivity;
import com.example.star.view.center.PendingEvaluationActivity;
import com.example.star.view.center.RechargeActivity;
import com.example.star.view.center.SettingsActivity;
import com.example.star.view.center.ShoppingCartActivity;
import com.example.star.view.center.FavoritesActivity;
import com.example.star.view.center.AllOrdersActivity;
import com.example.star.view.center.PendingPaymentActivity;
import com.example.star.view.center.PendingReceiptActivity;
import com.example.star.view.center.UploadSongActivity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CenterFragment extends Fragment {

    private TextView tvUsername, moneyText;
    private ImageView loginAvatar;
    private Button btnSettings;
    private Button btnSongs;
    private Button btnRecharge, btnShoppingCart, btnFavorites, btnFollows;
    private Button btnAllOrders, btnPendingPayment, btnPendingReceipt, btnPendingEvaluation, btnFinish;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_center, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvUsername = view.findViewById(R.id.tv_username);
        loginAvatar = view.findViewById(R.id.login_avatar);
        btnSettings = view.findViewById(R.id.btn_settings);
        btnSongs = view.findViewById(R.id.btn_songs);
        btnRecharge = view.findViewById(R.id.btn_recharge);
        btnShoppingCart = view.findViewById(R.id.btn_shopping_cart);
        btnFavorites = view.findViewById(R.id.btn_favorites);
        btnFollows = view.findViewById(R.id.btn_follows);
        btnAllOrders = view.findViewById(R.id.btn_all_orders);
        btnPendingPayment = view.findViewById(R.id.btn_pending_payment);
        btnPendingReceipt = view.findViewById(R.id.btn_pending_receipt);
        btnPendingEvaluation = view.findViewById(R.id.btn_pending_evaluation);
        btnFinish = view.findViewById(R.id.btn_finish);
        moneyText = view.findViewById(R.id.money);

        // 从 SharedPreferences 获取用户名
        String username = getUsernameFromSharedPreferences();
        if (username != null) {
            tvUsername.setText(username);
            getAndDisplayUserInfo(username);
        }

        // 点击后跳转到更改头像
        loginAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), ChangeAvatarActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到设置页面
        btnSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), SettingsActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到上传歌曲页面
        btnSongs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), UploadSongActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到充值中心页面
        btnRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), RechargeActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到购物车页面
        btnShoppingCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), ShoppingCartActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到收藏页面
        btnFavorites.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), FavoritesActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到关注页面
        btnFollows.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), FollowActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到全部订单页面
        btnAllOrders.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), AllOrdersActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到待付款页面
        btnPendingPayment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), PendingPaymentActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到待收货页面
        btnPendingReceipt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), PendingReceiptActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到待评价页面
        btnPendingEvaluation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), PendingEvaluationActivity.class);
                    startActivity(intent);
                }
            }
        });

        // 点击后跳转到已完成页面
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAdded()) {
                    Intent intent = new Intent(requireContext(), FinishActivity.class);
                    startActivity(intent);
                }
            }
        });

    }

    private String getUsernameFromSharedPreferences() {
        if (isAdded()) {
            SharedPreferences sharedPreferences = requireContext().getSharedPreferences("user_info", Context.MODE_PRIVATE);
            return sharedPreferences.getString("username", null);
        }
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 当从修改页面返回时刷新头像
        String username = getUsernameFromSharedPreferences();
        if (username != null) {
            getAndDisplayUserInfo(username);
        }
    }

    private void getAndDisplayUserInfo(String username) {
        if (isAdded()) {
            ApiUser apiUser = ApiClient.getApiUser();
            apiUser.getUserByUsername(username).enqueue(new Callback<User>() {
                @Override
                public void onResponse(Call<User> call, Response<User> response) {
                    if (isAdded() && response.isSuccessful() && response.body() != null) {
                        User user = response.body();

                        // 获取图片
                        Glide.with(requireContext())
                                .load(user.getAvatar())
                                .placeholder(R.drawable.register)
                                .error(R.drawable.register)
                                .into(loginAvatar);

                        moneyText.setText(String.valueOf(user.getMoney()));
                    }
                }

                @Override
                public void onFailure(Call<User> call, Throwable t) {
                    if (isAdded()) {
                        Toast.makeText(requireContext(), "加载信息失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
}